import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/login'
import store from "@/store"
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: () => import('@/views/layout/index.vue'),
    redirect: '/home',
    children: [
      {
        path: 'home',
        component: () => import('@/views/layout/home/index.vue'),
      },
      {
        path: 'user-info',
        component: () => import('@/views/layout//PersonalCenter/user-info.vue'),
      },
      {
        path: 'user-avatar',
        component: () => import('@/views/layout/PersonalCenter/user-avatar'),
      },
      {
        path: 'user-pwd',
        component: () => import('@/views/layout/PersonalCenter/user-pwd.vue'),
      },
      {
        path: 'art-cate',
        component: () => import('@/views/layout/art/art-cate.vue'),
      },
      {
        path: 'art-list',
        component: () => import('@/views/layout/art/art-list.vue'),
      },

    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/register')
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import('../views/layout')
  },
  {
    path: '/401',
    name: '401',
    component: () => import('@/components/401')
  },
]


const router = new VueRouter({
  routes
})
// 导航守卫
let fangxing = ['/login', '/register']
router.beforeEach((to, from, next) => {
  let token = store.state.login.token
  // ...方法一：调用vuex里的actions发起用户信息请求（在layout里已发（方法二）
  /* if (token && !store.state.userInfo.username) {
    store.dispatch('getUserInfo')
    console.log(11)
  }
  next() */
  // --方法一：
  if (!fangxing.includes(to.path)) {
    if (token) {
      return next()
    } else {
      next('/login')
    }
  } else {
    next()
  }
  /*//--方法二   if (token) {
      next()
    } else {
      if (fangxing.includes(to.path)) {
        next()
      } else {
        next('login')
      }
    } */

})
export default router
